/**
 * 导出所有预设数据到JSON文件
 * 包括内存数据库中的用户数据和文件中的数据
 */

const fs = require('fs');
const path = require('path');
const bcrypt = require('bcrypt');

// 创建导出目录
const exportDir = path.join(__dirname, 'exported-data');
if (!fs.existsSync(exportDir)) {
  fs.mkdirSync(exportDir);
}

console.log('📦 开始导出所有预设数据...');
console.log('');

// ========== 1. 导出预设用户数据 ==========
async function exportUsers() {
  console.log('👥 导出预设用户数据...');
  
  const users = [
    {
      id: 'u001',
      username: 'jiangjiankai',
      password: await bcrypt.hash('jjk123456', 10),
      name: '姜建凯',
      email: 'jiangjiankai@hospital.com',
      role: 'admin',
      department: '信息科',
      position: '系统管理员',
      phone: '13800000001',
      created_at: new Date().toISOString(),
      has_face: true
    },
    {
      id: 'u002',
      username: 'guomengzhe', 
      password: await bcrypt.hash('gmz123456', 10),
      name: '郭梦哲',
      email: 'guomengzhe@hospital.com',
      role: 'admin',
      department: '院办',
      position: '院长',
      phone: '13800000002',
      created_at: new Date().toISOString(),
      has_face: false
    },
    {
      id: 'u003',
      username: 'zhangyiwe',
      password: await bcrypt.hash('zyw123456', 10),
      name: '张译文',
      email: 'zhangyiwe@hospital.com',
      role: 'user',
      department: '内科',
      position: '内科主任',
      phone: '13800000003',
      created_at: new Date().toISOString(),
      has_face: false
    },
    {
      id: 'u004',
      username: 'yaoyuan',
      password: await bcrypt.hash('yy123456', 10),
      name: '姚远',
      email: 'yaoyuan@hospital.com',
      role: 'user',
      department: '内科',
      position: '主治医师',
      phone: '13800000004',
      created_at: new Date().toISOString(),
      has_face: false
    },
    {
      id: 'u005',
      username: 'limengran',
      password: await bcrypt.hash('lmr123456', 10),
      name: '李梦然',
      email: 'limengran@hospital.com',
      role: 'user',
      department: '内科',
      position: '主管护师',
      phone: '13800000005',
      created_at: new Date().toISOString(),
      has_face: false
    }
  ];
  
  // 保存用户数据
  fs.writeFileSync(
    path.join(exportDir, 'users.json'),
    JSON.stringify(users, null, 2),
    'utf-8'
  );
  
  // 保存用户明文密码（仅用于导入）
  const userPasswords = users.map(user => ({
    id: user.id,
    username: user.username,
    name: user.name,
    email: user.email,
    role: user.role,
    department: user.department,
    position: user.position,
    phone: user.phone,
    plainPassword: getPlainPassword(user.username)
  }));
  
  fs.writeFileSync(
    path.join(exportDir, 'users-with-passwords.json'),
    JSON.stringify(userPasswords, null, 2),
    'utf-8'
  );
  
  console.log(`  ✅ 导出 ${users.length} 个用户到 users.json`);
  console.log(`  ✅ 导出用户密码信息到 users-with-passwords.json`);
}

function getPlainPassword(username) {
  const passwords = {
    'jiangjiankai': 'jjk123456',
    'guomengzhe': 'gmz123456',
    'zhangyiwe': 'zyw123456',
    'yaoyuan': 'yy123456',
    'limengran': 'lmr123456'
  };
  return passwords[username] || 'unknown';
}

// ========== 2. 复制现有数据文件 ==========
function copyExistingData() {
  console.log('📁 复制现有数据文件...');
  
  const filesToCopy = [
    {
      source: 'face_data.json',
      target: 'face-data.json',
      description: '人脸识别数据'
    },
    {
      source: 'src/config/ocr-config.json',
      target: 'ocr-config.json', 
      description: 'OCR配置'
    },
    {
      source: '../h5/src/app/(main)/dashboard/data.json',
      target: 'dashboard-data.json',
      description: '仪表板任务数据'
    },
    {
      source: '../h5/src/app/(main)/dashboard/medical-data.json',
      target: 'medical-alerts.json',
      description: '医疗告警数据'
    }
  ];
  
  filesToCopy.forEach(file => {
    const sourcePath = path.join(__dirname, file.source);
    const targetPath = path.join(exportDir, file.target);
    
    if (fs.existsSync(sourcePath)) {
      fs.copyFileSync(sourcePath, targetPath);
      console.log(`  ✅ 复制 ${file.description}: ${file.target}`);
    } else {
      console.log(`  ⚠️ 文件不存在: ${file.source}`);
    }
  });
}

// ========== 3. 创建医疗设备数据 ==========
function createMedicalEquipmentData() {
  console.log('🏥 创建医疗设备数据...');
  
  const equipment = [
    {
      id: 'eq_001',
      name: 'CT-01',
      type: 'ct',
      location: '影像科A区',
      status: 'active',
      description: '64排螺旋CT',
      specifications: '64排，层厚0.5mm',
      manufacturer: 'GE Healthcare',
      installDate: '2023-01-15',
      lastMaintenance: '2024-12-01',
      nextMaintenance: '2025-03-01'
    },
    {
      id: 'eq_002',
      name: 'MRI-01',
      type: 'mri',
      location: '影像科B区',
      status: 'active',
      description: '3.0T磁共振成像设备',
      specifications: '3.0T，32通道',
      manufacturer: 'Siemens',
      installDate: '2023-03-20',
      lastMaintenance: '2024-11-15',
      nextMaintenance: '2025-02-15'
    },
    {
      id: 'eq_003',
      name: 'X光机-02',
      type: 'xray',
      location: 'L2放射科',
      status: 'active',
      description: 'DR数字化X光机',
      specifications: '14×17英寸探测器',
      manufacturer: 'Philips',
      installDate: '2023-05-10',
      lastMaintenance: '2024-12-05',
      nextMaintenance: '2025-03-05'
    },
    {
      id: 'eq_004',
      name: '呼吸机-ICU-01',
      type: 'ventilator',
      location: 'ICU病房',
      status: 'active',
      description: '有创无创一体化呼吸机',
      specifications: '支持多种通气模式',
      manufacturer: 'Dräger',
      installDate: '2023-02-28',
      lastMaintenance: '2024-11-28',
      nextMaintenance: '2025-02-28'
    },
    {
      id: 'eq_005',
      name: '超声设备-01',
      type: 'ultrasound',
      location: '超声科',
      status: 'active',
      description: '彩色多普勒超声诊断仪',
      specifications: '全数字化，高清成像',
      manufacturer: 'Mindray',
      installDate: '2023-04-12',
      lastMaintenance: '2024-10-12',
      nextMaintenance: '2025-01-12'
    }
  ];
  
  fs.writeFileSync(
    path.join(exportDir, 'medical-equipment.json'),
    JSON.stringify(equipment, null, 2),
    'utf-8'
  );
  
  console.log(`  ✅ 创建 ${equipment.length} 个医疗设备数据`);
}

// ========== 4. 创建科室数据 ==========
function createDepartmentData() {
  console.log('🏢 创建科室数据...');
  
  const departments = [
    {
      id: 'dept_001',
      name: '急诊科',
      type: 'emergency',
      location: '1楼东区',
      director: '李主任',
      phone: '0571-12345678',
      hours: '24小时',
      capacity: 50,
      status: 'active',
      description: '24小时急诊医疗服务'
    },
    {
      id: 'dept_002',
      name: '内科',
      type: 'inpatient',
      location: '2楼北区',
      director: '张译文',
      phone: '0571-12345679',
      hours: '8:00-17:00',
      capacity: 100,
      status: 'active',
      description: '内科诊疗服务'
    },
    {
      id: 'dept_003',
      name: '影像科',
      type: 'radiology',
      location: '1楼西区',
      director: '王主任',
      phone: '0571-12345680',
      hours: '8:00-18:00',
      capacity: 30,
      status: 'active',
      description: 'CT、MRI、X光检查服务'
    },
    {
      id: 'dept_004',
      name: 'ICU',
      type: 'surgery',
      location: '3楼',
      director: '陈主任',
      phone: '0571-12345681',
      hours: '24小时',
      capacity: 20,
      status: 'active',
      description: '重症监护病房'
    },
    {
      id: 'dept_005',
      name: '药房',
      type: 'pharmacy',
      location: '1楼南区',
      director: '刘主任',
      phone: '0571-12345682',
      hours: '8:00-20:00',
      capacity: 10,
      status: 'active',
      description: '中心药房，药品配发'
    }
  ];
  
  fs.writeFileSync(
    path.join(exportDir, 'departments.json'),
    JSON.stringify(departments, null, 2),
    'utf-8'
  );
  
  console.log(`  ✅ 创建 ${departments.length} 个科室数据`);
}

// ========== 5. 创建权限和角色数据 ==========
function createRolePermissionData() {
  console.log('🔐 创建权限和角色数据...');
  
  const roles = [
    {
      role: 'admin',
      name: '管理员',
      description: '系统管理员，拥有所有权限',
      permissions: [
        'view_dashboard',
        'view_realtime_data',
        'view_system_status', 
        'view_device_monitoring',
        'view_analytics',
        'view_patient_management',
        'view_department_management',
        'edit_patient_info',
        'edit_department_info',
        'view_optimization',
        'create_optimization',
        'approve_optimization',
        'view_scenarios',
        'create_scenarios',
        'edit_scenarios',
        'delete_scenarios',
        'manage_permissions',
        'manage_users',
        'system_settings'
      ]
    },
    {
      role: 'user',
      name: '普通用户',
      description: '普通医护人员',
      permissions: [
        'view_dashboard',
        'view_realtime_data',
        'view_analytics',
        'view_patient_management',
        'edit_patient_info',
        'view_scenarios'
      ]
    }
  ];
  
  fs.writeFileSync(
    path.join(exportDir, 'roles-permissions.json'),
    JSON.stringify(roles, null, 2),
    'utf-8'
  );
  
  console.log(`  ✅ 创建 ${roles.length} 个角色权限配置`);
}

// ========== 6. 创建系统配置数据 ==========
function createSystemConfig() {
  console.log('⚙️ 创建系统配置数据...');
  
  const config = {
    hospital: {
      name: '医疗数字孪生系统',
      version: '1.0.0',
      description: '基于数字孪生技术的智慧医院管理平台'
    },
    database: {
      mongodb: {
        uri: 'mongodb+srv://1191665779:20020219aa@zn.apmsejq.mongodb.net/medical_digital_twin',
        dbName: 'medical_digital_twin'
      }
    },
    features: {
      faceRecognition: true,
      ocrProcessing: true,
      realTimeMonitoring: true,
      alertManagement: true,
      equipmentTracking: true
    },
    defaults: {
      sessionTimeout: 3600,
      maxFileSize: '10MB',
      supportedImageTypes: ['jpg', 'jpeg', 'png'],
      defaultLanguage: 'zh-CN'
    }
  };
  
  fs.writeFileSync(
    path.join(exportDir, 'system-config.json'),
    JSON.stringify(config, null, 2),
    'utf-8'
  );
  
  console.log('  ✅ 创建系统配置文件');
}

// ========== 7. 创建数据说明文档 ==========
function createDataDocumentation() {
  console.log('📖 创建数据说明文档...');
  
  const documentation = {
    exportInfo: {
      exportDate: new Date().toISOString(),
      exportVersion: '1.0.0',
      description: '医疗数字孪生系统预设数据导出'
    },
    files: {
      'users.json': '用户数据（加密密码）',
      'users-with-passwords.json': '用户数据（含明文密码，仅用于导入）',
      'face-data.json': '人脸识别特征数据',
      'medical-alerts.json': '医疗告警示例数据',
      'medical-equipment.json': '医疗设备数据',
      'departments.json': '科室部门数据',
      'roles-permissions.json': '角色权限配置',
      'dashboard-data.json': '仪表板任务数据',
      'ocr-config.json': 'OCR服务配置',
      'system-config.json': '系统配置参数'
    },
    importInstructions: {
      step1: '确保MongoDB已连接',
      step2: '运行 npm run migrate 执行数据迁移',
      step3: '验证数据导入结果',
      step4: '启动服务器测试功能'
    },
    userAccounts: [
      {
        username: 'jiangjiankai',
        password: 'jjk123456',
        role: 'admin',
        description: '超级管理员账号'
      },
      {
        username: 'guomengzhe', 
        password: 'gmz123456',
        role: 'admin',
        description: '院长账号'
      },
      {
        username: 'zhangyiwe',
        password: 'zyw123456',
        role: 'user',
        description: '内科主任账号'
      },
      {
        username: 'yaoyuan',
        password: 'yy123456', 
        role: 'user',
        description: '医生账号'
      },
      {
        username: 'limengran',
        password: 'lmr123456',
        role: 'user',
        description: '护士账号'
      }
    ]
  };
  
  fs.writeFileSync(
    path.join(exportDir, 'README.json'),
    JSON.stringify(documentation, null, 2),
    'utf-8'
  );
  
  console.log('  ✅ 创建数据说明文档');
}

// ========== 执行导出 ==========
async function runExport() {
  try {
    await exportUsers();
    copyExistingData();
    createMedicalEquipmentData();
    createDepartmentData();
    createRolePermissionData();
    createSystemConfig();
    createDataDocumentation();
    
    console.log('');
    console.log('🎉 数据导出完成！');
    console.log('');
    console.log('📁 导出文件位置:', exportDir);
    console.log('');
    console.log('📋 导出的文件:');
    
    const files = fs.readdirSync(exportDir);
    files.forEach(file => {
      const filePath = path.join(exportDir, file);
      const stats = fs.statSync(filePath);
      const sizeKB = (stats.size / 1024).toFixed(2);
      console.log(`  - ${file} (${sizeKB} KB)`);
    });
    
    console.log('');
    console.log('💡 使用说明:');
    console.log('  1. 查看 README.json 了解详细说明');
    console.log('  2. users-with-passwords.json 包含明文密码，仅用于参考');
    console.log('  3. 运行 npm run migrate 将数据导入 MongoDB');
    
  } catch (error) {
    console.error('❌ 导出失败:', error);
  }
}

// 运行导出
runExport();